package servlet;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import javafx.scene.input.KeyCodeCombination;
import model.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.BaseServlet;
import utils.SmsUtil;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;


@WebServlet("/register.do")
public class RegisteredServlet extends BaseServlet {
        private UserService userService = new UserServiceImpl();
        public String reg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
            String msg = "注册失败";
           String phone = request.getParameter("phone");
            String code = request.getParameter("code");
            String password = request.getParameter("password");
            HttpSession session = request.getSession();
            User user = userService.findUserByPhone(phone);
            PrintWriter out = response.getWriter();
           if (user!=null){
               out.write(JSON.toJSONString(msg));
               return "r:register.html";
           }else{
               User addUser = new User();
               addUser.setPhone(phone);
               addUser.setPassword(password);
               addUser.setName(phone);
               userService.add(addUser);
               session.setAttribute("user",userService.findUserByPhone(phone));
               return "r:xiaomi/index.html";
           }
        }
        public void getCode(HttpServletRequest request,HttpServletResponse response) throws ClientException {
            String code = SmsUtil.getNewcode();
            request.getSession().setAttribute("code",code);
            String phone = request.getParameter("phone");
            SmsUtil.sendSms(phone,code);
        }

}
